import os
from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                             QPushButton, QFileDialog, QSpinBox, QComboBox,
                             QColorDialog, QGroupBox, QProgressBar, QTextEdit,
                             QMessageBox, QCheckBox)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QTime
from PyQt5.QtGui import QColor
from app.core.subtitle_burner import SubtitleBurner


class SubtitleExportDialog(QDialog):
    """字幕导出对话框"""
    
    def __init__(self, subtitles, parent=None):
        super().__init__(parent)
        self.subtitles = subtitles
        self.subtitle_burner = SubtitleBurner()
        self.video_path = ""
        self.output_path = ""
        
        self.init_ui()
        
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("导出带字幕的视频")
        self.setModal(True)
        self.resize(600, 500)
        
        layout = QVBoxLayout()
        
        # 视频选择组
        video_group = QGroupBox("视频文件")
        video_layout = QVBoxLayout()
        
        # 输入视频
        input_layout = QHBoxLayout()
        input_layout.addWidget(QLabel("输入视频:"))
        self.video_path_label = QLabel("未选择视频文件")
        self.video_path_label.setStyleSheet("color: gray;")
        input_layout.addWidget(self.video_path_label)
        self.select_video_btn = QPushButton("选择视频")
        self.select_video_btn.clicked.connect(self.select_video)
        input_layout.addWidget(self.select_video_btn)
        video_layout.addLayout(input_layout)
        
        # 输出路径
        output_layout = QHBoxLayout()
        output_layout.addWidget(QLabel("输出路径:"))
        self.output_path_label = QLabel("未设置输出路径")
        self.output_path_label.setStyleSheet("color: gray;")
        output_layout.addWidget(self.output_path_label)
        self.select_output_btn = QPushButton("选择路径")
        self.select_output_btn.clicked.connect(self.select_output)
        output_layout.addWidget(self.select_output_btn)
        video_layout.addLayout(output_layout)
        
        video_group.setLayout(video_layout)
        layout.addWidget(video_group)
        
        # 字幕样式组
        style_group = QGroupBox("字幕样式")
        style_layout = QVBoxLayout()
        
        # 字体大小
        font_size_layout = QHBoxLayout()
        font_size_layout.addWidget(QLabel("字体大小:"))
        self.font_size_spin = QSpinBox()
        self.font_size_spin.setRange(12, 72)
        self.font_size_spin.setValue(24)
        font_size_layout.addWidget(self.font_size_spin)
        font_size_layout.addStretch()
        style_layout.addLayout(font_size_layout)
        
        # 字体颜色
        font_color_layout = QHBoxLayout()
        font_color_layout.addWidget(QLabel("字体颜色:"))
        self.font_color_btn = QPushButton()
        self.font_color_btn.setFixedSize(60, 25)
        self.font_color_btn.setStyleSheet("background-color: white; border: 1px solid black;")
        self.font_color_btn.clicked.connect(self.select_font_color)
        font_color_layout.addWidget(self.font_color_btn)
        font_color_layout.addStretch()
        style_layout.addLayout(font_color_layout)
        
        # 描边颜色
        outline_color_layout = QHBoxLayout()
        outline_color_layout.addWidget(QLabel("描边颜色:"))
        self.outline_color_btn = QPushButton()
        self.outline_color_btn.setFixedSize(60, 25)
        self.outline_color_btn.setStyleSheet("background-color: black; border: 1px solid black;")
        self.outline_color_btn.clicked.connect(self.select_outline_color)
        outline_color_layout.addWidget(self.outline_color_btn)
        outline_color_layout.addStretch()
        style_layout.addLayout(outline_color_layout)
        
        # 描边宽度
        outline_width_layout = QHBoxLayout()
        outline_width_layout.addWidget(QLabel("描边宽度:"))
        self.outline_width_spin = QSpinBox()
        self.outline_width_spin.setRange(0, 10)
        self.outline_width_spin.setValue(2)
        outline_width_layout.addWidget(self.outline_width_spin)
        outline_width_layout.addStretch()
        style_layout.addLayout(outline_width_layout)
        
        style_group.setLayout(style_layout)
        layout.addWidget(style_group)
        
        # 导出选项组
        options_group = QGroupBox("导出选项")
        options_layout = QVBoxLayout()
        
        # 创建SRT文件
        self.create_srt_checkbox = QCheckBox("同时创建SRT字幕文件")
        self.create_srt_checkbox.setChecked(True)
        options_layout.addWidget(self.create_srt_checkbox)
        
        # 验证字幕
        self.validate_checkbox = QCheckBox("导出前验证字幕时间")
        self.validate_checkbox.setChecked(True)
        options_layout.addWidget(self.validate_checkbox)
        
        options_group.setLayout(options_layout)
        layout.addWidget(options_group)
        
        # 进度条
        progress_group = QGroupBox("导出进度")
        progress_layout = QVBoxLayout()
        
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        progress_layout.addWidget(self.progress_bar)
        
        self.status_text = QTextEdit()
        self.status_text.setMaximumHeight(100)
        self.status_text.setVisible(False)
        progress_layout.addWidget(self.status_text)
        
        progress_group.setLayout(progress_layout)
        layout.addWidget(progress_group)
        
        # 按钮组
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        self.export_btn = QPushButton("开始导出")
        self.export_btn.clicked.connect(self.start_export)
        self.export_btn.setEnabled(False)
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        
        button_layout.addWidget(self.export_btn)
        button_layout.addWidget(self.cancel_btn)
        
        layout.addLayout(button_layout)
        
        self.setLayout(layout)
        
        # 初始化颜色
        self.font_color = QColor(255, 255, 255)  # 白色
        self.outline_color = QColor(0, 0, 0)     # 黑色
        
    def select_video(self):
        """选择输入视频文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择视频文件", "", 
            "视频文件 (*.mp4 *.avi *.mov *.mkv *.wmv *.flv);;所有文件 (*.*)"
        )
        
        if file_path:
            self.video_path = file_path
            self.video_path_label.setText(os.path.basename(file_path))
            self.video_path_label.setStyleSheet("color: black;")
            
            # 自动设置输出路径
            if not self.output_path:
                base_name = os.path.splitext(file_path)[0]
                self.output_path = f"{base_name}_with_subtitles.mp4"
                self.output_path_label.setText(os.path.basename(self.output_path))
                self.output_path_label.setStyleSheet("color: black;")
                
            self.check_export_ready()
            
    def select_output(self):
        """选择输出路径"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存视频文件", "", 
            "MP4视频文件 (*.mp4);;所有文件 (*.*)"
        )
        
        if file_path:
            self.output_path = file_path
            self.output_path_label.setText(os.path.basename(file_path))
            self.output_path_label.setStyleSheet("color: black;")
            self.check_export_ready()
            
    def select_font_color(self):
        """选择字体颜色"""
        color = QColorDialog.getColor(self.font_color, self)
        if color.isValid():
            self.font_color = color
            self.font_color_btn.setStyleSheet(f"background-color: {color.name()}; border: 1px solid black;")
            
    def select_outline_color(self):
        """选择描边颜色"""
        color = QColorDialog.getColor(self.outline_color, self)
        if color.isValid():
            self.outline_color = color
            self.outline_color_btn.setStyleSheet(f"background-color: {color.name()}; border: 1px solid black;")
            
    def check_export_ready(self):
        """检查是否可以开始导出"""
        if self.video_path and self.output_path:
            self.export_btn.setEnabled(True)
        else:
            self.export_btn.setEnabled(False)
            
    def start_export(self):
        """开始导出"""
        if not self.subtitles:
            QMessageBox.warning(self, "警告", "没有字幕内容可以导出")
            return
            
        # 验证字幕
        if self.validate_checkbox.isChecked():
            success, video_info = self.subtitle_burner.get_video_info(self.video_path)
            if not success:
                QMessageBox.critical(self, "错误", f"无法获取视频信息: {video_info}")
                return
                
            errors = self.subtitle_burner.validate_subtitles(self.subtitles, video_info['duration'])
            if errors:
                error_text = "\n".join(errors)
                QMessageBox.warning(self, "字幕验证失败", f"发现以下问题:\n{error_text}")
                return
                
        # 创建SRT文件
        if self.create_srt_checkbox.isChecked():
            srt_path = os.path.splitext(self.output_path)[0] + ".srt"
            success, message = self.subtitle_burner.create_srt_file(self.subtitles, srt_path)
            if not success:
                QMessageBox.warning(self, "警告", f"创建SRT文件失败: {message}")
                
        # 开始导出视频
        self.export_btn.setEnabled(False)
        self.progress_bar.setVisible(True)
        self.status_text.setVisible(True)
        self.status_text.append("开始导出视频...")
        
        # 创建导出线程
        self.export_thread = ExportThread(
            self.subtitle_burner,
            self.video_path,
            self.subtitles,
            self.output_path,
            self.font_size_spin.value(),
            self.font_color.name(),
            self.outline_color.name(),
            self.outline_width_spin.value()
        )
        
        self.export_thread.progress_updated.connect(self.update_progress)
        self.export_thread.status_updated.connect(self.update_status)
        self.export_thread.export_finished.connect(self.export_finished)
        
        self.export_thread.start()
        
    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(value)
        
    def update_status(self, message):
        """更新状态信息"""
        self.status_text.append(message)
        
    def export_finished(self, success, message):
        """导出完成"""
        self.progress_bar.setVisible(False)
        self.status_text.setVisible(False)
        self.export_btn.setEnabled(True)
        
        if success:
            QMessageBox.information(self, "成功", message)
            self.accept()
        else:
            QMessageBox.critical(self, "错误", message)
            
        # 清理线程
        if hasattr(self, 'export_thread'):
            self.export_thread.quit()
            self.export_thread.wait()


class ExportThread(QThread):
    """导出线程"""
    
    progress_updated = pyqtSignal(int)
    status_updated = pyqtSignal(str)
    export_finished = pyqtSignal(bool, str)
    
    def __init__(self, subtitle_burner, video_path, subtitles, output_path,
                 font_size, font_color, outline_color, outline_width):
        super().__init__()
        self.subtitle_burner = subtitle_burner
        self.video_path = video_path
        self.subtitles = subtitles
        self.output_path = output_path
        self.font_size = font_size
        self.font_color = font_color
        self.outline_color = outline_color
        self.outline_width = outline_width
        
    def run(self):
        """运行导出任务"""
        try:
            self.status_updated.emit("正在加载视频...")
            self.progress_updated.emit(10)
            
            self.status_updated.emit("正在处理字幕...")
            self.progress_updated.emit(30)
            
            self.status_updated.emit("正在合成视频...")
            self.progress_updated.emit(50)
            
            self.status_updated.emit("正在编码视频...")
            self.progress_updated.emit(70)
            
            # 调用字幕烧录器
            success, message = self.subtitle_burner.burn_subtitles_to_video(
                self.video_path,
                self.subtitles,
                self.output_path,
                self.font_size,
                self.font_color,
                self.outline_color,
                self.outline_width
            )
            
            if success:
                self.progress_updated.emit(100)
                self.status_updated.emit("导出完成!")
                self.export_finished.emit(True, message)
            else:
                self.export_finished.emit(False, message)
                
        except Exception as e:
            self.export_finished.emit(False, f"导出过程中发生错误: {str(e)}") 